package cn.sdormitory.controller.academic;

import cn.sdormitory.academic.entity.ClsPracticeInfo;
import cn.sdormitory.academic.entity.ClsPracticeResult;
import cn.sdormitory.academic.service.ClsPracticeInfoService;
import cn.sdormitory.academic.service.ClsPracticeResultService;
import cn.sdormitory.academic.vo.ClsPracticeInfoQueryVo;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.common.api.CommonPage;
import cn.sdormitory.common.api.CommonResult;
import cn.sdormitory.common.exception.ApiException;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("/academic/cls/practice/info")
public class ClsPracticeInfoController {

    @Autowired
    ClsPracticeInfoService clsPracticeInfoService;

    @Autowired
    ClsPracticeResultService clsPracticeResultService;

    @PostMapping("/findPageList")
    public CommonResult findPageList(@RequestBody ClsPracticeInfoQueryVo vo){
        IPage<ClsPracticeInfo> pageList = clsPracticeInfoService.findPageList(vo);
        return CommonResult.success(CommonPage.restPage(pageList));
    }

    @PostMapping("/createOrUpdate")
    public CommonResult createOrUpdate(@RequestBody ClsPracticeInfo clsPracticeInfo){
        Boolean flag = clsPracticeInfoService.createOrUpdate(clsPracticeInfo);
        if(flag){
            return CommonResult.success();
        }else {
            return CommonResult.failed();
        }
    }

    @GetMapping("/exportSingleClsPractice/{clsPracticeInfoId}")
    public CommonResult exportSingleClsPractice(HttpServletResponse response, @PathVariable("clsPracticeInfoId") Long clsPracticeInfoId){
        ClsPracticeInfo clsPracticeInfo = clsPracticeInfoService.findById(clsPracticeInfoId);
        List<ClsPracticeResult> clsPracticeResults = clsPracticeResultService.findListByClsPracticeByInfoId(clsPracticeInfoId);
//        EasyExcel.write(response.getOutputStream(), BStudent.class).sheet("学生名单").doWrite(exportList);
        try {
            String templatePath = this.getClass().getClassLoader().getResource("templates/singleClsPracticeTemplate.xlsx").getPath();
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                    .withTemplate(templatePath).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

            //表头数据
            excelWriter.fill(clsPracticeInfo ,fillConfig, writeSheet);
            //主体数据
            List<FillWrapper> fillWrappers = new LinkedList<>();
            fillWrappers.add(new FillWrapper("result",clsPracticeResults));
            fillWrappers.forEach(v->{
                excelWriter.fill(v, fillConfig, writeSheet);
            });
            excelWriter.finish();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
        }
        return CommonResult.failed();
    }

    @PostMapping("/exportMultipleClsPractice")
    public CommonResult exportMultipleClsPractice(HttpServletResponse response,@RequestBody ClsPracticeInfoQueryVo vo){
        if(vo.getClassId() == null){
            return CommonResult.failed("请选择班级后导出");
        }
        List<ClsPracticeInfo> clsPracticeInfoList = clsPracticeInfoService.findClsPracticeInfo(vo);

        //表头
        List<List<String>> head = new LinkedList<>();
        //表格主题内容
        List<List<String>> body = new LinkedList<>();

        //生成前两列固定表头
        List<String> head0 = new ArrayList<>();
        head0.add("学号");
        head0.add("学号");
        head.add(head0);
        List<String> head1 = new ArrayList<>();
        head1.add("学生姓名");
        head1.add("学生姓名");
        head.add(head1);

        //填充数据
        for(int i = 0; i < clsPracticeInfoList.size();i ++){
            //表头数据
            List<String> infoExportData = new ArrayList<>();
            infoExportData.add(clsPracticeInfoList.get(i).getClsPracticeName());
            infoExportData.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(clsPracticeInfoList.get(i).getCreateTime()));
            head.add(infoExportData);
            //内容数据（循环多少次代表除固定表头的两列外的列数）
            List<ClsPracticeResult> clsPracticeResultList = clsPracticeResultService.findListByClsPracticeByInfoId(clsPracticeInfoList.get(i).getId());
            //取第一列的数据时候，创建出存在有多少行数据，后续为每行数据补充其剩余列下面所缺失的数据
            if(i == 0){
                for(ClsPracticeResult item : clsPracticeResultList){
                    List<String> resultExportData = new LinkedList<>();
                    resultExportData.add(item.getStudentNo());
                    resultExportData.add(item.getStudentName());
                    resultExportData.add(item.getIsPass());
                    body.add(resultExportData);
                }
            }else {
                //后续数据根据最外层循环取得对应info下得result
                for (int k = 0; k < body.size(); k++) {
                    body.get(k).add(clsPracticeResultList.get(i).getIsPass());
                }
            }
        }
        try{
            EasyExcel.write(response.getOutputStream()).head(head).sheet().doWrite(body);
            return CommonResult.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return CommonResult.failed();
    }

}
